<template>
  <el-form :model="form" :rules="rules">
    <el-form-item prop="email">
      <el-input v-model="form.email" placeholder="请输入邮箱" prop="email"></el-input>
    </el-form-item>
    <el-form-item prop="emailCode">
      <el-input
      v-model="form.emailCode"
      placeholder="请输入邮箱验证码"
      style="margin-top: 1rem"
      prop="emailCode"
    >
      <template #append>
        <el-button @click="sendEmailCode">发送验证码</el-button>
      </template>
    </el-input>
    </el-form-item>
    
    <el-button type="primary" style="width: 100%; margin-top: 1rem" @click="login"
      >登录</el-button
    >
  </el-form>
</template>

<script setup>
import { ref } from "vue";
import { getEmailCodeAPI } from '@/apis/user'
import { ElMessage } from "element-plus";

const form = ref({
  email: "",
  emailCode: "",
});

const emit = defineEmits(["login"]);

const login = () => {
  emit("login", { email: form.value.email, code: form.value.emailCode });
};

const sendEmailCode = () => {
  if (!form.value.email) {
    ElMessage.error("请输入邮箱");
    return;
  }
  getEmailCodeAPI({
    email: form.value.email
  }).then(res => {
    ElMessage.success(res.message);
  }).catch(err => {
    ElMessage.error("验证码发送失败");
    console.log(err);
  })
};

const rules = {
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  emailCode: [
    {
      required: true,
      message: "请输入邮箱验证码",
      trigger: "blur",
    },
  ],
};
</script>
